package com.starry.core.base

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.BarUtils
import com.starry.core.R
import com.starry.core.utils.ActivityController
import com.starry.core.viewmodel.BaseViewModel
import com.starry.core.ext.getApplicationViewModel
import com.starry.core.utils.ZKStatusBarUtil
import java.lang.reflect.ParameterizedType


abstract class BaseActivity
<VB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
    companion object {
        private const val TAG: String = "BaseActivity"
    }

    /**
     * 控制是否需要添加状态栏的高度
     * 默认不设置
     */
    open val shouldAddStatusHeight: Boolean = true

    /**
     * 通过反射拿到ViewModel并且注册
     */
    protected val mViewModel: VM by lazy {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[1] as Class<VM>
        aClass.getDeclaredConstructor().isAccessible = true
        if (useViewModelApplication()) {
            getApplicationViewModel(application, aClass)
        } else {
            ViewModelProvider(this)[aClass]
        }
    }

    /**
     * 通过反射拿到DataBinding
     */
    protected val mDataBinding: VB by lazy {
        val type = javaClass.genericSuperclass as ParameterizedType
        val aClass = type.actualTypeArguments[0] as Class<*>
        val method = aClass.getDeclaredMethod("inflate", LayoutInflater::class.java)
        method.isAccessible = true
        method.invoke(null, layoutInflater) as VB
    }


    /**
     * ViewModel是否绑定Application生命周期
     */
    protected open fun useViewModelApplication(): Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "onCreate: ${javaClass.simpleName}")
        ActivityController.addActivity(this)
        initActivity()
    }

    /**
     * 是否展示toolBar
     * 默认展示toolBar
     */
    open fun isToolbarVisible(): Boolean {
        return true
    }

    /**
     * 初始化Activity
     */
    private fun initActivity() {
        //私有的初始化DataBinding 和 ViewModel
        initLayout()
        //初始化布局
        initView()
        //初始化数据
        initData()
    }

    protected abstract fun initData()

    protected abstract fun initView()


    protected abstract fun getLayoutId(): Int

    private fun initLayout() {
        //支持LiveData绑定xml，数据改变，UI自动更新
        mDataBinding.lifecycleOwner = this
//        ZKStatusBarUtil.setTransparentForWindow(this)
        //初始化toolBar
        if (isToolbarVisible()) {
            setContentView(R.layout.activity_base)
            initToolbar()
            val contentFl = findViewById<FrameLayout>(R.id.flContent)
            contentFl.removeAllViews()
            contentFl.addView(mDataBinding.root)
        } else {
            setContentView(mDataBinding.root)
        }
        //修改状态栏的高度
        if (shouldAddStatusHeight) {
            adjustForStatusBarHeight()
        }
    }

    /**
     * 调整布局来适应状态栏的高度
     */
    private fun adjustForStatusBarHeight() {
        val statusBarHeight = ZKStatusBarUtil.getStatusBarHeight(getContext())
        if (isToolbarVisible()) {
            val rootLl = findViewById<LinearLayout>(R.id.rootBaseContent)
            val params = rootLl.layoutParams as ViewGroup.MarginLayoutParams
            params.topMargin = statusBarHeight
            rootLl.layoutParams = params
        } else {
            val params = mDataBinding.root.layoutParams as ViewGroup.MarginLayoutParams
            params.topMargin = statusBarHeight
            mDataBinding.root.layoutParams = params
        }
    }

    /**
     * 子类实现设置Toolbar的标题
     */
    open fun getToolbarTitle(): String = "Toolbar"

    /**
     * 子类可选择重写实现自定义的Toolbar样式
     */
    protected fun getToolbar(): Toolbar = findViewById(R.id.toolBar)

    /**
     * 是否启用返回按钮
     * 默认启用
     */
    open fun isDisplayHomeAsUpEnable(): Boolean = true

    private fun initToolbar() {
        if (isToolbarVisible()) {
            val toolbar: Toolbar = getToolbar()
            setSupportActionBar(toolbar)
            if (isDisplayHomeAsUpEnable()) {
                supportActionBar?.setDisplayHomeAsUpEnabled(true)
            }
            toolbar.setNavigationOnClickListener { onBackPressed() }
            val toolbarTitle = getToolbarTitle()
            val tvTitle = toolbar.findViewById<TextView>(R.id.tvToolbarTitle)
            if (TextUtils.isEmpty(toolbarTitle)) {
                tvTitle.visibility = View.GONE
            } else {
                tvTitle.visibility = View.VISIBLE
                tvTitle.text = toolbarTitle
            }
        }
    }

    fun getContext() = this
    override fun onDestroy() {
        super.onDestroy()
        mDataBinding.unbind()
        ActivityController.removeActivity(this)
    }


}
